const db = require('../config/db')
const staffModel = '../schema/staff'
const Mall = db.MallSequelize    //引入数据库
const staff = Mall.import(staffModel)   //使用import方法，实例化user

// 获取员工列表
const getStaffs = async (query) => {
  let page = Number(query.page)
  let limit = Number(query.limit)
  const result = await staff.findAndCountAll(
    {
      offset: parseInt(page*10)*parseInt(limit/10),
      limit: limit,
      order: [['updated_at', 'desc']]
    }
  )
  return result
}

// 根据id获取员工列表
const getStaffById = async (data) => {
  const result = await staff.findAll(
    {
      where: {id: data}
    }
  )
  return result
}

// 根据id修改员工列表
const updateStaff = async (data, id) => {
  const result = await staff.update(
    {
      name: data.name,
      mobile: data.mobile,
      gender: data.gender,
      create_time: data.create_time,
      update_time: data.update_time,
      remark: data.remark,
      image_url: data.image_url
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
// 根据搜索关键字获取员工
const getStaffByKeyWords = async (keywords) => {
  if(keywords.id) {
    const result = await staff.findAll(
      { 
        where: {
          id: Number(keywords.id)
        } 
      },
    )
    return result
  }else if(keywords.name) {
    const result = await staff.findAll(
      { 
        where: {
          name: keywords.name
        } 
      },
    )
    return result
  }
}
// 新增员工
const addStaff = async (data) => {
  console.log(data)
  await staff.create({
      name: data.name,
      mobile: data.mobile,
      gender: data.gender,
      remark: data.remark,
      status: 1,
      image_url: data.image_url
  })
  return true
}

// 根据id删除员工
const deleteStaff = async (data) => {
  await staff.destroy({
      where: {
        id: data
      }
  })
  return true
}

// 根据id更新员工状态
const updateStatus = async (data, id) => {
  await staff.update(
    {
      status: data.status
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
module.exports = {
  getStaffs,
  getStaffById,
  updateStaff,
  getStaffByKeyWords,
  addStaff,
  deleteStaff,
  updateStatus
}